package biz

import (
	"flag"
	"log"
	"os"
	"runtime"
	"strings"
)

type path struct {
	Dir     string
	AppName string
	Port    string

	Splitter string

	dirAbsolute bool
	dirEmpty    bool
}

func (p *path) GetPath() {
	pa := flag.String("path", "", "安装路径")
	name := flag.String("app", "", "项目名称")
	port := flag.String("port", "", "项目端口")

	flag.Parse()
	p.Dir = *pa
	p.AppName = *name
	p.Port = *port

	p.checkDir()
}

// checkPath
/**
 *  @Author: rym 2024-01-16 14:47:45
 *  @Description:j
 *  @receiver p
 */
func (p *path) checkDir() {
	//检查路径是否为绝对路径
	p.checkDirAbsolute()

	//检查按照目录是否为空
	p.checkDirIsEmpty()
}

// checkDirAbsolute
/**
 *  @Author: rym 2024-01-16 14:47:39
 *  @Description:检查路径是否为绝对路径
 *  @receiver p
 */
func (p *path) checkDirAbsolute() {
	p.dirAbsolute = false
	for k, v := range p.Dir {
		if (k == 0 && string(v) == "/") || (k == 1 && string(v) == ":") {
			//相对路径
			p.dirAbsolute = true
			break
		}
	}
}

// checkDirIsEmpty
/**
 *  @Author: rym 2024-01-16 15:03:29
 *  @Description:检查按照目录是否为空
 *  @receiver p
 */
func (p *path) checkDirIsEmpty() {
	var (
		goos    string
		dirList []os.DirEntry
		err     error
	)
	goos = runtime.GOOS

	p.Splitter = "/"

	if goos == "windows" {
		p.Dir = strings.ReplaceAll(p.Dir, "\\", "/")
	}

	absolute, _ := os.Getwd()
	if p.dirAbsolute == true {

	} else {
		p.Dir = strings.Trim(p.Dir, "./")
		p.Dir = strings.Trim(p.Dir, ".")
		p.Dir = absolute + p.Splitter + p.Dir
	}

	_, err = os.Stat(p.Dir)
	if err != nil {
		err = os.MkdirAll(p.Dir, 0766)
		if err != nil {
			log.Fatal("自动创建安装目录失败，请检查权限后重试", p.Dir)
		}
	}

	dirList, err = os.ReadDir(p.Dir)
	if err != nil {
		log.Fatal("读取安装目录失败，请检查权限后重试")
	}

	if len(dirList) > 0 {
		log.Fatal("安装目录不为空，请更换目录")
	}
}
